import { Tabs, Popup } from 'antd-mobile'
import { Icon } from '@/components/Icon'
import ArticleList from './components/ArticleList'

import styles from './index.module.scss'
import { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import { getChannels, changeChannels, getRestChannels } from '@/store/actions'
import { RootState } from '@/types/store'

import Channels from './Channels'
import { useInitialState } from '@/utils/use-initalState-store'
const Home = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  // 控制编辑弹窗
  const [isEdit, setIsedit] = useState(false)
  // 使用自定义hooks分发状态
  useInitialState(getChannels, 'home')

  // 获取可选频道
  useInitialState(getRestChannels, 'home')

  const { channels, activeId } = useSelector((state: RootState) => state.home)

  // 切换高亮
  const channelChange = (key: string) => {
    console.log(key)
    dispatch(changeChannels(+key))
  }

  return (
    <div className={styles.root}>
      {/* 频道 Tabs 列表 */}
      {channels.length > 0 && (
        <Tabs
          activeLineMode="fixed"
          className="tabs"
          activeKey={activeId + ''}
          onChange={channelChange}
          style={{
            '--fixed-active-line-width': '30px',
          }}
        >
          {channels.map((item) => (
            <Tabs.Tab
              title={item.name}
              key={item.id}
              style={{ height: '100%' }}
            >
              {/* 根据对应列表的id，可以获得各自列表的文章列表数据 */}
              <ArticleList channelId={item.id} />
            </Tabs.Tab>
          ))}
        </Tabs>
      )}

      <div className="tabs-opration">
        <Icon type="iconbtn_search" onClick={() => history.push('/search')} />
        <Icon type="iconbtn_channel" onClick={() => setIsedit(true)} />
      </div>
      {/* 编辑我的频道弹出层 */}
      <Popup visible={isEdit} position="left" className="channel-popup">
        <Channels onClose={() => setIsedit(false)} />
      </Popup>
    </div>
  )
}

export default Home
